
<style lang="stylus" scoped>
  ::selection{background:#000;color:#fff;}

  #appChat
    width 90%
    margin 0 auto
    padding-bottom 100px
    .scroll-top
      cursor pointer
      position fixed
      bottom 40px
      left 50%
      border-radius 50%
      background #fff
      font-size 18px
      overflow hidden
      width 40px
      height 40px
      line-height 40px
      user-select none
      text-align center
      transform rotate(-45deg) translateX(-50%)
      box-shadow 0 0 30px rgba(0,0,0,0.1);
      &:hover
        font-size 22px
  a
    color #0c5ed9
    text-decoration none
    font-size 12px
  .action
    margin-top 20px
    .lemon-button
      margin-right 10px
      margin-bottom 10px
  .link
    font-size 14px
    margin-top 15px
    a
      display inline-block
      margin 0 5px
      text-decoration none
      background #ffba00
      border-radius 4px
      padding 5px 10px
      color rgba(0,0,0,0.8)
  .logo
    position relative
    display inline-block
    margin 60px auto
    user-select none
  .logo-text
    font-size 38px
  .logo-sub
    font-size 18px
    color #999
    font-weight 300
  .logo-badge
    position absolute
    top -10px
    left 230px
    background #000
    border-radius 16px
    color #f9f9f9
    font-size 12px
    padding 4px 8px
  .title
    font-size 24px
    line-height 26px
    border-left 1px solid #ffba00
    padding-left 15px
    margin-bottom 15px
    margin-top 30px
    user-select none
  .table
    width 100%
    border-radius 10px
    background #fff
    border-collapse collapse
    tr
      cursor pointer
    tr:not(.table-head):hover
      background #ffba00 !important
    tr:nth-of-type(even)
      background #f9f9f9
    th
      user-select none
      color #999
    td,
    th
      text-align left
      padding 10px 15px
      font-size 14px
      font-weight normal
  .imui-center
    margin-bottom 60px
    .lemon-wrapper
      border:1px solid #ddd;
    .lemon-drawer
      border:1px solid #ddd;
      border-left:0;
  .drawer-content
    padding 15px
  .more
    font-size 12px
    line-height 24px
    height 24px
    position absolute
    top 14px
    right 14px
    cursor pointer
    user-select none
    color #f1f1f1
    display inline-block
    border-radius 4px
    background #111
    padding 0 8px
    &:active
      background #999
  .bar
    text-align center
    line-height 30px
    background #fff
    margin 15px
    color #666
    user-select none
    font-size 12px
  .cover
    text-align center
    user-select none
    position absolute
    top 50%
    left 50%
    transform translate(-50%,-50%)
    i
      font-size 84px
      color #e6e6e6
    p
      font-size 18px
      color #ddd
      line-height 50px
  .article-item
    line-height 34px
    cursor pointer
    &:hover
      text-decoration underline
      color #318efd
  pre
    background #fff
    border-radius 8px
    padding 15px
  .lemon-simple .lemon-container{
    z-index:5
  }
  .lemon-simple .lemon-drawer{
    z-index:4
  }



  input#switch[type=checkbox]{
    height: 0;
    width: 0;
    display:none;
  }

  label#switch-label {
    cursor: pointer;
    text-indent: -9999px;
    width: 34px;
    height: 20px;
    background: #aaa;
    display: block;
    border-radius: 100px;
    position: relative;
  }

  label#switch-label:after {
    content: '';
    position: absolute;
    top: 2px;
    left: 2px;
    width: 16px;
    height: 16px;
    background: #fff;
    border-radius: 20px;
    transition: 0.3s;
  }

  input#switch:checked + label {
    background: #0fd547;
  }

  input#switch:checked + label:after {
    left: calc(100% - 2px);
    transform: translateX(-100%);
  }

  label#switch-label:active:after {
    width: 20px;
  }
</style>

<template>
  <div id="appChat">

    <div class="imui-center">
      <lemon-imui
        :user="user"
        ref="IMUI"
        :contextmenu="contextmenu"
        :contact-contextmenu="contactContextmenu"
        :theme="theme"
        :hide-menu="true"
        :hide-menu-avatar="hideMenuAvatar"
        :hide-message-name="hideMessageName"
        :hide-message-time="hideMessageTime"
        @change-menu="handleChangeMenu"
        @change-contact="handleChangeContact"
        @pull-messages="handlePullMessages"
        @message-click="handleMessageClick"
        @menu-avatar-click="handleMenuAvatarClick"
        @send="handleSend"
      >
        <template #cover>
          <div class="cover">
            <i class="lemon-icon-message"></i>
            <p><b>自定义封面 Lemon</b> IMUI</p>
          </div>
        </template>
        <template #message-title="contact">
          <span>{{ contact.displayName }}</span>
          <small class="more" @click="changeDrawer(contact, $refs.IMUI)"
            >{{
              ($refs.IMUI ? $refs.IMUI.drawerVisible : false) ? "关闭" : "打开"
            }}话术/组织机构</small
          >
          <br />
        </template>
      </lemon-imui>


    </div>

  </div>
</template>

<script>
import Vue from "vue";
import store from '@/store/'
import LemonMessageVoice from "./lemon-message-voice";
import QQIMUI from "./qq";
import EmojiData from "./database/emoji";
import { getContactIMList,getUserIdByToken } from '@/api/api'
import { mapActions, mapMutations, mapGetters,mapState } from 'vuex'
import { uploadAction } from '@/api/manage'
Vue.component(LemonMessageVoice.name, LemonMessageVoice);
Vue.component(QQIMUI.name, QQIMUI);
let contactList = [];
const getTime = () => {
  return new Date().getTime();
};
const generateRandId = () => {
  return Math.random()
    .toString(36)
    .substr(-8);
};
const generateRandWord = () => {
  return Math.random()
    .toString(36)
    .substr(2);
};
const generateMessage = (toContactId = "", fromUser) => {
  if (!fromUser) {
    fromUser = {
      id: "system",
      displayName: "系统测试",
      avatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJl7b6XRdibAQeURZmmIqCq3ywz3JDibdQyzzP26u2xE0NkksRz72uVrwjYITp3ib7sC93LqpAHUGOPw/132",
    };
  }
  return {
    id: generateRandId(),
    status: "succeed",
    type: "text",
    sendTime: getTime(),
    content: generateRandWord(),
    //fileSize: 1231,
    //fileName: "asdasd.doc",
    toContactId,
    fromUser,
  };
};

export default {
  name: "appChat",
  data() {
    return {
      theme: "blue",
      contactContextmenu: [
        {
          text: "删除该聊天",
          click: (e, instance, hide) => {
            const { IMUI, contact } = instance;
            IMUI.updateContact({
              id: contact.id,
              lastContent: null,
            });
            if (IMUI.currentContactId == contact.id) IMUI.changeContact(null);
            hide();
          },
        },
        {
          text: "设置备注和标签",
        },
        {
          text: "投诉",
        },
        {
          icon: "lemon-icon-message",
          render: (h, instance, hide) => {
            return (
              <div style="display:flex;justify-content:space-between;align-items:center;width:130px">
                <span>加入黑名单</span>
                <span>
                  <input type="checkbox" id="switch" />
                  <label id="switch-label" for="switch">
                    Toggle
                  </label>
                </span>
              </div>
            );
          },
        },
        {
          click(e, instance, hide) {
            const { IMUI, contact } = instance;
            IMUI.removeContact(contact.id);
            if (IMUI.currentContactId == contact.id) IMUI.changeContact(null);
            hide();
          },
          color: "red",
          text: "删除好友",
        },
      ],
      contextmenu: [
        {
          click: (e, instance, hide) => {
            const { IMUI, message } = instance;
            const data = {
              id: generateRandId(),
              type: "event",
              //使用 jsx 时 click必须使用箭头函数（使上下文停留在vue内）
              content: (
                <div>
                  <span>
                    你撤回了一条消息{" "}
                    <span
                      v-show={message.type == "text"}
                      style="color:#333;cursor:pointer"
                      content={message.content}
                      on-click={e => {
                        IMUI.setEditorValue(e.target.getAttribute("content"));
                      }}
                    >
                      重新编辑
                    </span>
                  </span>
                </div>
              ),

              toContactId: message.toContactId,
              sendTime: getTime(),
            };
            IMUI.removeMessage(message.id);
            IMUI.appendMessage(data, true);
            hide();
          },
          visible: instance => {
            return instance.message.fromUser.id == this.user.id;
          },
          text: "撤回消息",
        },
        {
          visible: instance => {
            return instance.message.fromUser.id != this.user.id;
          },
          text: "举报",
        },
        {
          text: "转发",
        },
        {
          visible: instance => {
            return instance.message.type == "text";
          },
          text: "复制文字",
        },
        {
          visible: instance => {
            return instance.message.type == "image";
          },
          text: "在线预览",
          click:  (e, instance, hide) => {
            const { IMUI, message } = instance;
            this.encode(message.content).then(path => {
              let url = window._CONFIG['onlinePreviewDomainURL'] + '?url=' + encodeURIComponent(path)
              window.open(url, '_blank')
            })
            hide();
          },
        },
        {
          visible: instance => {
            return instance.message.type == "image";
          },
          text: "下载图片",
          click:  (e, instance, hide) => {
            const { IMUI, message } = instance;
            window.open(message.content, '_blank')
            hide();
          },
        },
        {
          visible: instance => {
            return instance.message.type == "file";
          },
          click:  (e, instance, hide) => {
            const { IMUI, message } = instance;
            console.log(message, 'file')
            this.encode(message.content).then(path => {
              let url = window._CONFIG['onlinePreviewDomainURL'] + '?url=' + encodeURIComponent(path)
              window.open(url, '_blank')
            })
            hide();
          },
          text: "在线预览",
        },
        {
          visible: instance => {
            return instance.message.type == "file";
          },
          click:  (e, instance, hide) => {
            const { IMUI, message } = instance;
            console.log(message, 'file')
            window.open(message.content, '_blank')
            hide();
          },
          text: "下载文件",
        },
        {
          click: (e, instance, hide) => {
            const { IMUI, message } = instance;
            IMUI.removeMessage(message.id);
            hide();
          },
          icon: "lemon-icon-folder",
          color: "red",
          text: "删除",
        },
      ],
      hideMenuAvatar: false,
      hideMenu: false,
      hideMessageName: false,
      hideMessageTime: true,
      user: {
        id: "1",
        displayName: "Tom",
        avatar: "",
      },
    };
  },
  created() {
      contactList = [];
      //TODO 获取在线人员
      getContactIMList({}).then(res=>{
          //设置当前登录人
          var userInfo = store.getters.userInfo;
          console.info("=====userInfo===:",userInfo)
          this.user.id = store.getters.userInfo.id;
          this.user.avatar = store.getters.userInfo.avatar;
          this.user.displayName = store.getters.userInfo.realname;
          if(res.result){
              for(var i =0;i < res.result.length;i ++){
                  if(res.result[i].id == store.getters.userInfo.id ){
                      //过滤当前登录人
                      //continue ;
                  }
                  contactList.push(res.result[i]);
              }
          }

      });
  },
  computed: {
    ...mapState({
      websocket: state => state.socket.websocket,
    })
  },

  mounted() {
      setTimeout(() => {
          console.info("====3000==");
          this.websocket.IMSocket = this.$refs.IMUI;
      },3000);

      /*
    setTimeout(() => {
        console.info("====5000==");
      // 关闭 并重新建立连接
      // this.websocket.close(); // 关闭 并重新建立连接  close会触发websocketOnclose方法
      // 发送 数据
      // 向后端发送数据  在websocketOnmessage中通过e.data可以获取到1122334455
      // this.websocket.send('1122334455');
      //debugger
      const data = {
              id: '唯一消息ID',
              status: 'succeed',
              type: 'text',
              sendTime: 1566047865417,
              content: '马上就对接完了！',
              toContactId: 2,
              fromUser:{
                  //如果 id == this.user.id消息会显示在右侧，否则在左侧
                  id:2,
                  displayName:'丽安娜',
                  avatar:'',
              }
      };
      // 在headerNotice.vue中的websocketOnmessage方法中通过e.data可以获取到data
      this.websocket.send(JSON.stringify(data));
    }, 5000);
    */

    setTimeout(() => {
        console.info("====10000==");
        this.appendCustomMessage();
    },10000);
    this.$nextTick(() => {
      const contactData1 = {
        id: "contact-1",
        displayName: "研发team群",
        avatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJl7b6XRdibAQeURZmmIqCq3ywz3JDibdQyzzP26u2xE0NkksRz72uVrwjYITp3ib7sC93LqpAHUGOPw/132",
        index: "[1]群组",
        unread: 0,
        lastSendTime: 1566047865417,
        lastContent: "2",
      };
      const contactData2 = {
        id: "contact-2",
        displayName: "自定义内容",
        avatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJl7b6XRdibAQeURZmmIqCq3ywz3JDibdQyzzP26u2xE0NkksRz72uVrwjYITp3ib7sC93LqpAHUGOPw/132",
        //index: "Z",
        click(next) {
          next();
        },
        renderContainer: () => {
          return <h1 style="text-indent:20px">自定义页面</h1>;
        },
        lastSendTime: 1345209465000,
        lastContent: "12312",
        unread: 2,
      };

      // const { IMUI } = this.$refs;
      let IMUI = this.$refs.IMUI;
      setTimeout(() => {
          IMUI.changeContact("contact-1");
          //通过ID 激活左侧 admin 用户
          //IMUI.changeContact("e9ca23d68d884d4ebb19d07889727dae");
      }, 500);

      IMUI.setLastContentRender("event", message => {
        return `[自定义通知内容]`;
      });
      /*
      let contactList = [
        { ...contactData1 },
        { ...contactData2 },
        //...Array(100).fill(contactData1)
      ];*/
      contactList.push(contactData1);
      console.info("====mounted =contactList:",JSON.stringify(contactList));
      //左侧 联系人信息
      IMUI.initContacts(contactList);
      IMUI.initMenus([
        {
          name: "messages",
        },
        {
          name: "contacts",
        },
        {
          name: "custom1",
          title: "自定义按钮1",
          unread: 0,
          render: menu => {
            return <i class="lemon-icon-attah" />;
          },
          renderContainer: () => {
            return (
              <div class="article">
                <ul>
                  <li class="article-item">
                    <h2>人民日报谈网红带货：产品真的值得买吗？</h2>
                  </li>
                </ul>
                <lemon-contact
                  props={{ contact: contactData1 }}
                  style="margin:20px"
                />
              </div>
            );
          },
          isBottom: true,
        },
        {
          name: "custom2",
          title: "自定义按钮2",
          unread: 0,
          click: () => {
            alert("拦截导航点击事件");
          },
          render: menu => {
            return <i class="lemon-icon-group" />;
          },
          isBottom: true,
        },
      ]);

      IMUI.initEditorTools([
        {
          name: "emoji",
        },
        {
          name: "uploadFile",
        },
        {
          name: "uploadImage",
        },
        /*{
          name: "test1",
          click: () => {
            IMUI.$refs.editor.selectFile("application/vnd.ms-excel");
          },
          render: () => {
            return <span>Excel</span>;
          },
        },
        {
          name: "test1",
          click: () => {
            IMUI.initEditorTools([{ name: "uploadFile" }, { name: "emoji" }]);
          },
          render: () => {
            return <span>重制工具栏</span>;
          },
        },*/
        /*{
          name: "test2",
          isRight: true,
          title: "上传 Excel",
          click: () => {
            alert("点击了 ··· ");
          },
          render: () => {
            return <b>扩展···</b>;
          },
        },*/
      ]);
      IMUI.initEmoji(EmojiData);

      IMUI.setLastContentRender("voice", message => {
        return <span>[语音]</span>;
      });

      // const { SimpleIMUI } = this.$refs;
      // contactData1.id = "11";
      // SimpleIMUI.initContacts([contactData1]);
      // SimpleIMUI.initEmoji(EmojiData);
      // SimpleIMUI.changeContact(contactData1.id);
    })
  },
  methods: {
    ...mapActions(['encode']),
    imOnmessage(e){
      //debugger;
      console.log("-----imOnmessage msg-------",e);
      if(e == undefined) {
          return;
      }
    },
    // ...mapMutations(["init_WebSocket", 'set_webSocket_open', 'set_webSocket_error', 'set_webSocket_message', 'set_webSocket_close']),
    changeTheme() {
      this.theme = this.theme == "default" ? "blue" : "default";
    },
    scrollToTop() {
      document.body.scrollIntoView();
    },
    handleMenuAvatarClick() {
      console.log("Event:menu-avatar-click");
    },
    handleMessageClick(e, key, message, instance) {
      console.log("点击了消息", e, key, message);
      //TODO 如果是文件 则下载 ，如果是图片 则放大
      if (key == "status") {
        instance.updateMessage({
          id: message.id,
          status: "going",
          content: "正在重新发送消息...",
        });
        setTimeout(() => {
          instance.updateMessage({
            id: message.id,
            status: "succeed",
            content: "发送成功",
          });
        }, 2000);
      }
    },
    changeMenuAvatarVisible() {
      this.hideMenuAvatar = !this.hideMenuAvatar;
    },
    changeMenuVisible() {
      this.hideMenu = !this.hideMenu;
    },
    changeMessageNameVisible() {
      this.hideMessageName = !this.hideMessageName;
    },
    changeMessageTimeVisible() {
      this.hideMessageTime = !this.hideMessageTime;
    },
    removeMessage() {
      const { IMUI } = this.$refs;
      const messages = IMUI.getCurrentMessages();
      const id = messages[messages.length - 1].id;
      if (messages.length > 0) {
        IMUI.removeMessage(id);
      }
    },
    updateMessage() {
      const { IMUI } = this.$refs;
      const messages = IMUI.getCurrentMessages();
      const message = messages[messages.length - 1];
      if (messages.length > 0) {
        const update = {
          id: message.id,
          status: "succeed",
          type: "file",
          fileName: "被修改成文件了.txt",
          fileSize: "4200000",
        };
        if (message.type == "event") {
          update.fromUser = this.user;
        }
        IMUI.updateMessage(update);
        IMUI.messageViewToBottom();
      }
    },
    appendCustomMessage() {
      console.info("=appendCustomMessage=")
      const { IMUI } = this.$refs;
      const message = {
        id: generateRandId(),
        status: "succeed",
        type: "text",
        sendTime: getTime(),
        content: "good消息",
        toContactId: "contact-1",
        fromUser: this.user,
      };
      IMUI.appendMessage(message, true);
    },
    appendMessage() {
      const { IMUI } = this.$refs;
      const contact = IMUI.currentContact;
      const message = generateMessage("contact-1");
      message.fromUser = {
        ...message.fromUser,
        ...this.user,
      };
      IMUI.appendMessage(message, true);
    },
    appendEventMessage() {
      const { IMUI } = this.$refs;
      const message = {
        id: generateRandId(),
        type: "event",
        content: (
          <span>
            邀请你加入群聊{" "}
            <span
              style="color:#333;cursor:pointer"
              on-click={() => alert("OK")}
            >
              接受
            </span>
          </span>
        ),
        toContactId: "contact-1",
        sendTime: getTime(),
      };
      IMUI.appendMessage(message, true);
    },
    updateContact() {
      this.$refs.IMUI.updateContact({
        id: "contact-1",
        unread: 10,
        displayName: generateRandWord(),
        lastSendTime: getTime(),
        lastContent: "修改昵称为随机字母",
      });
    },
    changeDrawer(contact, instance) {
      instance.changeDrawer({
        //width: 240,
        //height: "90%",
        //offsetX:0 ,
        //offsetY: ,
        //position: "center",
        // inside: true,
        // offsetX: -280,
        // offsetY: -100,
        render: () => {
          return (
            <div class="drawer-content">
              <p>
                <b>话术列表：</b>
              </p>
              <p>good1</p>
              <p>good2</p>
              <p>good3</p>
              <p>good</p>
              <hr />
              <p>
                <b>组织机构树：</b>
              </p>
              <p>{contact.displayName}</p>
              <p>张三</p>
              <p>赵四</p>
              <p>王五</p>
              <p>马六</p>
            </div>
          );
        },
      });
    },
    handleChangeContact(contact, instance) {
      console.log("Event:change-contact：",contact.id);
      instance.updateContact({
        id: contact.id,
        unread: 0,
      });
      instance.closeDrawer();
    },
    uploadFile: (file) => {
      return new Promise(resolve => {
        let formData = new FormData()
        formData.append('file', file);
        uploadAction(window._CONFIG['domianURL']+"/sys/oss/file/upload", formData).then((res) => {
          resolve(res)
        })
      })
    },
    handleSend(message, next, file) {
      console.log("handleSend:",message, next, file);
      setTimeout(() => {
        next();
      }, 1000);

      if(message.type == "text"){
          // ws send
          var msg ={};
          msg.toUserId= message.toContactId;
          msg.imMsg = message;
          this.websocket.send(JSON.stringify(msg));
          // 通过token 获取ID 再send
          /*getUserIdByToken(message.toContactId).then(res=>{
              console.info("===userId res.result:",res.result);
              if(res.result && res.result !="-1"){
                  var msg ={};
                  msg.toUserId= res.result;
                  msg.imMsg = message;
                  this.websocket.send(JSON.stringify(msg));
              }
          });*/
      }else if(message.type == "image" || message.type == "file"){
        //TODO 上传图片 至服务器并获取其URL地址
        console.log("cg handleSend222:",message, next, file);
        /*var tmp = '{"fromUser":{"displayName":"管理员","id":"e9ca23d68d884d4ebb19d07889727dae","avatar":"http://hl-picture.oss-cn-beijing.aliyuncs.com/logo/8.png"},"toContactId":"e9ca23d68d884d4ebb19d07889727dae","id":"807db04b-baab-4d8c-b951-6bb2297729b8","type":"image","content":"https://mall-oss-pic.oss-cn-beijing.aliyuncs.com/2022-06-30/规划_1656559844027.png","status":"going","sendTime":1656559843514}';
        //tmp ='{"fromUser":{"displayName":"管理员","id":"e9ca23d68d884d4ebb19d07889727dae","avatar":"http://hl-picture.oss-cn-beijing.aliyuncs.com/logo/8.png"},"toContactId":"e9ca23d68d884d4ebb19d07889727dae","id":"807db04b-baab-4d8c-b951-6bb2297729b8","type":"image","content":"blob:http://192.168.220.20:3000/b3a6923a-f228-405d-a2f8-0cff8259cf26","status":"going","sendTime":1656559843514}';
        message = JSON.parse(tmp);
        var msg ={};
        msg.toUserId= message.toContactId;
        msg.imMsg = message;
        this.websocket.send(JSON.stringify(msg));*/

        this.uploadFile(file).then(result => {
            console.info("===result:",result);
            if (result.success) {
              //设置 将图片URL地址 赋值给 消息体
              message.content=result.message;
              var msg ={};
              msg.toUserId= message.toContactId;
              msg.imMsg = message;
              this.websocket.send(JSON.stringify(msg));
          } else {
                console.log('上传失败！！')
          }
        })
      }


    },
    handlePullMessages(contact, next, instance) {
      console.info("====handlePullMessages:",instance.currentContactId);
      const otheruser = {
        id: contact.id,
        displayName: contact.displayName,
        avatar: contact.avatar,
      };
      setTimeout(() => {
        const messages = [
          //generateMessage(instance.currentContactId, this.user),
          //generateMessage(instance.currentContactId, otheruser),
          /*generateMessage(instance.currentContactId, this.user),
          {
            ...generateMessage(instance.currentContactId, this.user),
            ...{ status: "failed" },
          },*/
        ];
        console.info("=handlePullMessages=messages:",JSON.stringify(messages));
        next(messages, true);
      }, 500);
    },
    handleChangeMenu() {
      console.log("Event:change-menu");
    },
    openCustomContainer() {},

  },
};
</script>
